/*
 * @Description: 
 * @Author: cdtangxiejun
 * @version: 
 * @Date: 2023-01-06 16:13:37
 * @LastEditors: cdtangxiejun
 * @LastEditTime: 2023-08-21 20:56:08
 */
const fetch = require('../util/fetch')
const { logBook } = require('../util/log');
const tool = require('../util/tool.js');
const INTERFACE = require('../service/INTERFACE');

/**
 * 判断子路径是否是接口路由
 * @param path
 */
const isApiRouter = (path) => {
	if (
		path.startsWith('/sdk/edit') ||
		path.startsWith('/api')
	) {
		return true
	}
	return false
}

/**
 * 判断是否登录
 * @param ctx
 * @returns {Promise<{pin: pin}>}
 */
async function verify(ctx) {
	const { isOpView } = ctx.query;

	const data = {
		isOpView
	}
	const res = await fetch({
		ctx,
		data: data,
		method: 'GET',
		url: INTERFACE.isLogin,
	})
	const result = res.data
	if (result && result.success) {
		if (result.data && result.data.code == 200) {
			logBook.info('验证登录成功，用户为：' + result.data.nickName)
			return { pin: result.data.nickName };
		}
		else {
			// 如果是请求的接口，直接返回结果
			if (isApiRouter(ctx.url)) {
				ctx.send({ data: { code: 401, ...result.data } })
			}
			else {
				// 如果是页面进行重定向
				tool.redir(ctx);
			}
		}
	}
	else {
		logBook.error('验证登录失败：' + JSON.stringify(result));
		if (isApiRouter(ctx.url)) {
			ctx.send({ data: { code: 401, ...result } })
		}
		else {
			tool.redir(ctx);
		}
	}
}

/**
 * 拦截器
 * @param ctx
 * @param next
 * @returns {Promise<void>}
 * @constructor
 */
async function Interceptor(ctx, next) {
	const WHITE_PATH = ['/sdk/edit/saveModule', '/sdk/edit/deleteModule', '/favicon.ico']	// 命令行触发的添加模块操作不需要验证登录
	const { originalUrl } = ctx

	if (ctx.cookies.get('thor') || WHITE_PATH.includes(originalUrl)) {
		logBook.info('验证登录，thor存在，验证通过！');
		await next();
	}
	else {
		try {
			var user = await verify(ctx);
			if (user) {
				ctx.state.user = user;
				await next();
			}
		} catch (err) {
			logBook.error(err);
			tool.redir(ctx);
		}
	}
}

module.exports = Interceptor
